from rest_framework import views, status
from rest_framework.response import Response

from apps.app01.models import Order, User


class OrderListView(views.APIView):

    # 如果需要登录校验，可启用以下权限(示例使用 DRF 的认证和权限机制)
    # permission_classes = [IsAuthenticated]

    def get(self, request):
        # 1. 获取当前用户
        user_id = request.user["user_id"]
        # user = User.objects.first()  # 如果需要测试，可临时写死一个用户

        # if user.is_anonymous:
        #     return Response(
        #         {"code": 0, "message": "用户未登录", "data": []},
        #         status=status.HTTP_401_UNAUTHORIZED
        #     )

        # 2. 查询当前用户的所有订单，按创建时间倒序返回
        orders = Order.objects.filter(user=user_id).order_by('-id')

        # 3. 组装返回数据
        data_list = []
        for order in orders:
            # 订单包含的商品信息
            product_list = []
            for pc in order.products.all():  # order.products 是 M2M 到 ProductCount
                product_obj = pc.product  # 拿到真正的 Product 对象
                product_list.append({
                    "productId": product_obj.id,
                    "name": product_obj.name,
                    "price": pc.price,
                    "count": pc.count,
                    "picUrl": product_obj.pic_url.name if product_obj.pic_url else "",
                    "brief": product_obj.brief
                })

            data_list.append({
                "id": order.order_id,
                "recipientName": order.name,
                "products": product_list,
                "totalPrice": order.payment,
                "status": order.status
            })

        # 4. 返回响应
        return Response(
            {
                "code": 1,
                "message": "success",
                "data": data_list
            },
            status=status.HTTP_200_OK
        )